package sk.naive.talker.command;

import sk.naive.talker.*;
import sk.naive.talker.props.PropertyStoreException;
import sk.naive.talker.util.Utils;
import sk.naive.talker.message.DefaultMessageFactory;

import java.rmi.*;
import java.util.*;

/**
 *
 * @author <a href="mailto:richter@bgs.sk">Richard Richter</a>
 * @version $Revision: 1.41 $ $Date: 2005/03/16 21:42:54 $
 */

public class Who extends AbstractCommand {
	public void exec()
		throws RemoteException, PropertyStoreException
	{
		StringBuilder sb = new StringBuilder();
		long current = System.currentTimeMillis();
		ctxSet(DefaultMessageFactory.CTXKEY_VAL + "currentDate", Utils.createDate(current));
		sb.append(getString("who.head", user.getProperties()));

		Set<User> users = new TreeSet<User>(new Comparator() {
			public int compare(Object o1, Object o2) {
				return ((User) o1).getLogin().compareTo(((User) o2).getLogin());
			}
		});
		users.addAll(commandDispatcher.getUserFinder().onlineUsers());

		int count = 0;
		for (User u2 : users) {
			Location u2Loc = new LocationHelper(commandDispatcher).locationForUser(u2);
			if (u2Loc != null) {
				ctxSet(u2, DefaultMessageFactory.CTXKEY_VAL, u2Loc.getName());
			} else {
				ctxSet(u2, DefaultMessageFactory.CTXKEY_VAL, "N/A");
			}
			if (u2 == user) {
				sb.append(getString("who.selfline", u2.getProperties()));
			} else {
				long lastAction = (Long) u2.get(User.UPROP_LAST_ACTION_TIME);
				AfkStatus afkStatus = new AfkHelper(u2).getStatus();
				if (afkStatus != null) {
					lastAction = afkStatus.getAfkStart();
					if (afkStatus.getReason() != null) {
						ctxSet(u2, DefaultMessageFactory.CTXKEY_VAL + "AfkReason", afkStatus.getReason());
					}
				}
				long afkTime = Utils.createLong(current - lastAction, Consts.MINUTE_MILLIS);
				if (afkStatus != null || afkTime >= ((Integer) getTalker().get(Consts.TPROP_IDLE_TRESHOLD))) {
					ctxSet(u2, DefaultMessageFactory.CTXKEY_VAL + "AfkTime", afkTime);
				}
				sb.append(getString("who.line", u2.getProperties(), user.getLang()));
			}
			count++;
		}
		ctxSet(DefaultMessageFactory.CTXKEY_VAL, String.valueOf(count));
		sb.append(getString("who.tail", user.getProperties()));
		user.send(sb.toString());
	}
}
